const McMeetingUserRelation = require('./db/mc_meeting_user_relation.js')
const McMeeting = require('./db/mc_meeting')

const path = require('path');
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
import { AGCClient, CredentialParser } from "@agconnect/common-server"

// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientDW");
const agcClient = AGCClient.getInstance("clientDW");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);

//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}


let myHandler = async function (event, context, callback, logger) {
  const { code, userId } = event.body ? JSON.parse(event.body) : event

  // 查询会议是否已经过期
  const meetingQuery = clouddb.CloudDBZoneQuery.where(McMeeting.mc_meeting).equalTo("code", code)
  const respMeeting = await mCloudDBZone.executeQuery(meetingQuery);
  const meetings = respMeeting.getSnapshotObjects()

  if(meetings.length === 0) {
    callback({
      code: 400,
      desc: "请输入正确的会议口令"
    });
    return
  }

  const meeting = meetings[0]
  // 将时间戳转换为日期对象
  var date = new Date(meeting.startTime.getTime());

  // 加时间
  date.setMinutes(date.getMinutes() + meeting.duration);
  if(new Date().getTime() > date.getTime()) {
    callback({
      code: 400,
      desc: "该会议已结束，无法加入"
    });
    return
  }

  const mcRelation = clouddb.CloudDBZoneGenericObject.build("mc_meeting_user_relation")
  mcRelation.addFieldValue("id", generateUUID(), true);
  mcRelation.addFieldValue("meetingId", meeting.id);
  mcRelation.addFieldValue("userId", userId);
  mcRelation.addFieldValue("startTime", meeting.startTime);

  await mCloudDBZone.executeUpsert(mcRelation);

  callback({
    code: 200,
    meetingId: meeting.id,
    desc: "成功"
  });
};

export { myHandler };